﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft Corp." file="CreateDatabaseOperation.cs">
//   All rights reserved. See License.txt in the project root for license information.
// </copyright>
// 
// --------------------------------------------------------------------------------------------------------------------
namespace CloudBlitz.DeploymentManager.DeploymentOperations
{
    using System;
    using System.Linq;

    using CloudBlitz.DeploymentManager.DeploymentWorkflow;

    public class CreateDatabaseOperation : DeploymentOperationBase
    {
        private readonly Func<SqlAzureServerCredentials, ISqlAzureServerManager> sqlAzureServerManagerFactory;

        public CreateDatabaseOperation(Func<SqlAzureServerCredentials, ISqlAzureServerManager> sqlAzureServerManagerFactory) : base(2)
        {
            this.sqlAzureServerManagerFactory = sqlAzureServerManagerFactory;
        }

        protected override OperationResult ExecuteOverride(DeploymentContext context)
        {
            var sqlAzureServerManager = this.sqlAzureServerManagerFactory(context.SqlServerDetails.Credentials);

            try
            {
                this.RaiseProgressChangedEvent(0, "Creating SQL database");

                var databases = sqlAzureServerManager.ListDatabases(context.SqlServerDetails.Name);
                if (!databases.Any(x => x.Equals(context.SqlServerDetails.DatabaseName)))
                {
                    sqlAzureServerManager.CreateDatabase(
                                                context.SqlServerDetails.Name,
                                                context.SqlServerDetails.DatabaseName,
                                                context.SqlServerDetails.MaxSizeInGb);

                    this.RaiseProgressChangedEvent(100, string.Format("SQL database \"{0}\" created on server \"{1}\"", context.SqlServerDetails.DatabaseName, context.SqlServerDetails.Name));
                }
                else
                {
                    this.RaiseProgressChangedEvent(100, string.Format("SQL database \"{0}\" already exists on server \"{1}\"", context.SqlServerDetails.DatabaseName, context.SqlServerDetails.Name));
                }
            }
            catch (Exception e)
            {
                return ExceptionHelper.HandleException(e);
            }

            return OperationResult.Success;
        }
    }
}